package WIAB::Controller::Uploads;

use strict;
use warnings;
use base 'Catalyst::Controller';
use Path::Class;
use File::Basename;
=head1 NAME

WIAB::Controller::Uploads - Catalyst Controller

=head1 SYNOPSIS

See L<WIAB>

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=head2 METHODS

=head2 auto

Make sure the user is logged in.  Forwards to Controller::Edit for that function (cut paste code is bad)

=cut

sub auto : Private {
    my ($self, $c) = @_;
    unless ($c->user) {
        $c->detach('WIAB::Controller::Edit', 'auto');
        return;
    }
}

sub index : Private {
    my ($self, $c) = @_;
    my $static_root = Path::Class::Dir->new($c->config->{root})->subdir('static');
    my $files = WIAB::Model::Content->get_rss_file_list($static_root, ['uploads']);
    foreach my $f  (@$files) {
        $f = basename("$f");
    }
    $c->stash->{files}= $files;
    $c->stash->{template} = 'upload.tt';
}

sub do_upload : Local {
    my ($self, $c) = @_;
    my $upload_dir =  Path::Class::Dir->new($c->config->{root})->subdir('static')->subdir('uploads');
    my $upload = $c->req->upload('f');
    my $max_size = 10485760;
    if ($upload->size > $max_size) {
        $c->res->body('file is larger than maximum size allowed, use your back button to go back');
        return;
    }
    else {
        my $file = $upload->filename;
        my $dest = $upload_dir->file($file);
        if (-e $dest) {
            $c->res->body("$file already exists, please go back, check and rename if necessary");
            return;
        }
        else {
            $upload->copy_to("$dest");
            $c->res->redirect($c->uri_for("/uploads"));
        }
    }
}

=head1 AUTHOR

Kieren Diment

=head1 LICENSE

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;
